package com.sunday.common.mq.kafka.study.spring.e13_Serialization_Deserialization_Message_Conversion_Topic;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * {@link org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration}
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class MQApi {

    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    @GetMapping("/send/{topic}/{key}")
    public void send(@PathVariable String topic, @PathVariable String key) throws InterruptedException, ExecutionException {
        sendTypeMsg(topic, key, sendTypeRand(key));
    }

    public void sendTypeMsg(String topic, String key, Object value) throws ExecutionException, InterruptedException {
        CompletableFuture<SendResult<Object, Object>> future;
        log.info("msg type : {}", value.getClass());
        future = kafkaTemplate.send(topic, key, value);
        log.info("[send result] : {}", future.get());
    }

    public Object sendTypeRand(String key) {
        if (Integer.valueOf(key) < 2) {
            return "byte======".getBytes();
        } else {
            return "string======";
        }

    }

}
